import traceback

from sanic import HTTPResponse, Request, SanicException
from sanic.handlers import ErrorHandler
from sanic.log import logger
from apps.base.response import CustomerResponse


Return_Code_dict = {
    200: "无错误",
    10001: "参数不正确",
    10002: "模型接口请求错误",
}


# 自定义错误
class AppError(SanicException):
    def __init__(self, error_code, debug_info=''):
        self.error_code = error_code
        self.message = Return_Code_dict[error_code]
        self.debug = debug_info if debug_info else Return_Code_dict[error_code]


# 自定义错误处理
class CustomErrorHandler(ErrorHandler):
    def default(self, request: Request, exception: Exception) -> HTTPResponse:
        # 自定义错误
        if isinstance(exception, AppError):
            logger.error('loco_error, code:{0}, debug:{1}'.format(exception.error_code, exception.debug))
            return CustomerResponse(code=exception.error_code, message=exception.message)
        # 系统错误
        else:
            logger.error('error: ' + traceback.format_exc())
            return CustomerResponse(code=500, message='服务器内部错误')
